<?php

namespace App\Kuafu\Invoice\Service;

use App\Kuafu\Common\Service\EncryptService;
use App\Kuafu\Config\Model\ConfigModel;
use App\Kuafu\Invoice\Enum\InvoiceCodeEnum;
use App\Kuafu\Invoice\Exceptions\InvoiceException;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Model\OrderInvoiceModel;
use App\Kuafu\Order\Model\OrderSplitModel;
use App\Kuafu\Order\Service\OrderInvoiceService;
use App\Kuafu\Order\Service\OrderService;
use App\Kuafu\Shop\Service\ShopInvoiceService;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use Illuminate\Support\Facades\Log;

class InvoiceService
{
    const FPLXDM = '026'; //发票种类026电子普票,028电子专票,004纸质专票,007纸质普票
    const SPMC   = '餐饮服务'; //商品名称，最大长度100
    const HSBZ   = 1; //含税标志(0否，1是)，默认1

    /**
     * 内部跳转 请求盟度
     * @param $orderId
     * @throws InvoiceException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function jumpUrl($orderId)
    {
        if (config('app.env') == 'dev' || config('app.env') == 'qa') {
            return 'https://www.kuafood.com';
        }
        //获取解密订单id
        $orderId = EncryptService::decryptOrderId($orderId);
        if (!$orderId) {
            throw new InvoiceException(InvoiceCodeEnum::ERR_NO_ORDER);
        }
        //判断订单来源
        $orderType = OrderInvoiceService::getInvoiceType($orderId);
        $orderId   = $orderType['orderId'];
        $shopId    = $orderType['shopId'];
        //判断订单已经开票
        $invoiceInfo = OrderInvoiceService::getInvoiceInfoById($orderId, $shopId,
            OrderInvoiceModel::ORDER_INVOICE_STATUS_VALID);
        if ($invoiceInfo) {
            return $invoiceInfo['invoiceUrl'];
        }
        //判断最新一条记录是否是待开票
        $invoiceInfo = OrderInvoiceService::getInvoiceInfoById($orderId, $shopId);
        if ($invoiceInfo && $invoiceInfo['status'] == OrderInvoiceModel::ORDER_INVOICE_STATUS_APPLY) {
            return $invoiceInfo['invoiceUrl'];
        }
        //获取店铺信息
        $shopInfo = ShopInvoiceService::getShopInvoiceInfo($shopId);
        if (empty($shopInfo)) {
            return 'https://www.kuafood.com';
        }
        if ($orderType['type'] == OrderInvoiceModel::ORDER_INVOICE_DB_ORDER_TYPE_POS) {
            //获取订单信息
            $orderInfo = OrderSplitModel::suffix($shopId)
                                        ->query()
                                        ->where('orderId', $orderId)
                                        ->first();
            $je        = $orderInfo['realPayPrice'] / 100;
        } elseif ($orderType['type'] == OrderInvoiceModel::ORDER_INVOICE_DB_ORDER_TYPE_WAIMAI) {
            $orderInfo = WaiMaiOrderModel::suffix($shopId)
                                         ->query()
                                         ->where('orderId', $orderId)
                                         ->first();
            $je        = $orderInfo['payPrice'] / 100;
        }
        if ($je <= 0) {
            return 'https://www.kuafood.com';
        }
        $slv      = $shopInfo['fee'] / 100; //税率，小数格式，如:0.06
        $syyhzcbz = $shopInfo['isDiscount']; //优惠政策标志(0否，1是)，默认0
        $yhzcsm   = $shopInfo['discountName']; //优惠政策说明
        //获取店铺发票相关信息
        $fplxdm = self::FPLXDM;
        $spmc   = self::SPMC;
        $hsbz   = self::HSBZ;
        $spbm   = config('moredo.SPBM'); //税收分类编码，标准19位
        //获取xml 扫码
        $spxx = MoredoBaseService::getApplyInvoiceV2SpxxXml($fplxdm, $spmc, $je, $slv, $hsbz, $spbm, $syyhzcbz,
            $yhzcsm);
        //添加税盘
        //MoredoBaseService::addDevice($shopInfo['invoiceNo'], $shopInfo['kpjh']);
        //申请开票
        $moredoId = OrderInvoiceService::encOrderId($orderId, $orderType['type'], $shopId);
        //获取当前请求盟度订单号次数
        $count    = OrderInvoiceModel::query()
                                     ->where('orderId', $orderType['orderId'])
                                     ->count();
        $count    = $count + 1;
        $moredoId = $moredoId . '-' . $count;
        Log::channel('invoice')->info('盟度扫码订单号' . $moredoId);
        $applyInvoice = MoredoBaseService::applyInvoiceV2($moredoId, $spxx, $shopInfo['invoiceNo'], $shopInfo['kpjh']);
        //生成扫码地址后 生成数据库记录以便下次扫码直接进入
        $insertData = [
            'orderId'    => $orderId,
            'shopId'     => $shopId,
            'orderType'  => $orderType['type'],
            'invoiceUrl' => $applyInvoice['data']['qrcode'] ?? '',
            'status'     => OrderInvoiceModel::ORDER_INVOICE_STATUS_APPLY,
            'supplier'   => OrderInvoiceModel::ORDER_INVOICE_DB_SUPPLIER_MERODO,
        ];
        Log::channel('invoice')->info("盟度开票回调信息-扫码" . json_encode($insertData, JSON_UNESCAPED_UNICODE));
        OrderInvoiceService::addInvoiceData($insertData);
        return $applyInvoice['data']['qrcode'] ?? '';
    }

    /**
     * 处理开票回调结果
     * @param $xml
     * @return mixed
     */
    public static function uploadCallbackDataHandle($xml)
    {
        try {
            $decode    = base64_decode($xml);
            $iconv     = iconv("GB2312", "UTF-8//IGNORE", $decode);
            $replace   = str_replace("GBK", "UTF-8", $iconv);
            $xmlstring = simplexml_load_string($replace, 'SimpleXMLElement', LIBXML_NOCDATA);
            return json_decode(json_encode($xmlstring), true);
        } catch (\Exception $exception) {
            Log::channel('invoice')->info("盟度开票回调信息-解析失败:" . $exception->getMessage());
            throw new InvoiceException(InvoiceCodeEnum::ERR_ANALYSIS);
        }

    }

    /**
     * 业务红冲
     * @param $shopId
     * @param $orderId
     * @throws InvoiceException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function redInvoiceOrder(
        $shopId,
        $orderId,
        $operateSource = CodeEnum::ORDER_OUT_INVOICE_SOURCE_NORMAL
    ) {
        $shopInfo = ShopInvoiceService::getShopInvoiceInfo($shopId);
        if (empty($shopInfo)) {
            throw new InvoiceException(InvoiceCodeEnum::ERR_SHOP_NOT_INVOICE);
        }
        //获取最新一条数据记录
        $newInvoice = OrderInvoiceService::getInvoiceInfoById($orderId, $shopId);
        if (empty($newInvoice)) {
            throw new InvoiceException(InvoiceCodeEnum::ERR_NO_ORDER);
        }
        $count         = OrderInvoiceModel::query()
                                          ->where('orderId', $orderId)
                                          ->count();
        $moredoOrderId = OrderInvoiceService::encOrderId($orderId, $newInvoice['orderType'], $shopId);
        $moredoOrderId = $moredoOrderId . '-' . $count;
        Log::channel('invoice')->info('盟度主动取消' . $moredoOrderId);
        if ($newInvoice['status'] == OrderInvoiceModel::ORDER_INVOICE_STATUS_VALID) {
            //如果有 查询是否有红冲记录
            $redInfo = OrderInvoiceService::getInvoiceInfoById($orderId,
                OrderInvoiceModel::ORDER_INVOICE_STATUS_RED_CANCELED);
            if (!empty($redInfo)) {
                throw new InvoiceException(InvoiceCodeEnum::ERR_EXIST_RED_ORDER);
            } else {
                MoredoBaseService::redInvoice($shopInfo['invoiceNo'], $shopInfo['kpjh'], $moredoOrderId,
                    $newInvoice['fpdm'],
                    $newInvoice['fphm'], $newInvoice['fplxdm']);
            }
        } elseif ($newInvoice['status'] == OrderInvoiceModel::ORDER_INVOICE_STATUS_APPLY) {
            //取消开票
            MoredoBaseService::cancelInvoice($shopInfo['invoiceNo'], $shopInfo['kpjh'], $moredoOrderId);
            //修改取消数据库类型
            $field = ['status' => OrderInvoiceModel::ORDER_INVOICE_STATUS_CANCEL, 'operateSource' => $operateSource];
            OrderInvoiceService::updateFieldByOrderId($newInvoice['id'], $field);
        }

        return [
            'recallStatus' => true
        ];
    }


    /**
     * 订货开票门店内测
     * @param int $shopId
     * @return bool
     */
    public static function checkIsAllowInvoice(int $shopId): bool
    {
        $data = ConfigModel::getConfigByTypeKeyOne("kfosInvoiceShopIdList", "invoiceShopList", 600);
        $arr  = json_decode($data->value, true)??[];
        if (empty($arr) || in_array($shopId, $arr)) {
            return true;
        }
        return false;
    }


}
